package com.kitten.dataAlign.job;

import com.kitten.dataAlign.constants.TableConstants;
import com.kitten.dataAlign.domain.mapper.CreateTableMapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author kitten
 * @description 自动创建日增量计数变更表
 */
@Slf4j
@Component
@RefreshScope
public class CreateTableXxlJob {

    @Value("${table.shards}")
    private int tableShards;

    @Resource
    private CreateTableMapper createTableMapper;

    @XxlJob("createTableJobHandler")
    public void createTableJobHandler() throws Exception {
        String date = LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern("yyyyMMdd")); // 获取明日日期

        XxlJobHelper.log("##    开始初始化明日增量数据表");

        if (tableShards > 0) {
            for(int shardKey = 0; shardKey < tableShards; shardKey++) {
                String tableNameSuffix = TableConstants.buildTableNameSuffix(date, shardKey);   // 表名后缀
                // 创建数据表
                createTableMapper.createDataAlignFollowingCountTempTable(tableNameSuffix);
                createTableMapper.createDataAlignFansCountTempTable(tableNameSuffix);
                createTableMapper.createDataAlignNoteLikeCountTempTable(tableNameSuffix);
                createTableMapper.createDataAlignNoteCollectCountTempTable(tableNameSuffix);
                createTableMapper.createDataAlignUserLikeCountTempTable(tableNameSuffix);
                createTableMapper.createDataAlignUserCollectCountTempTable(tableNameSuffix);
                createTableMapper.createDataAlignUserPublishNoteCountTempTable(tableNameSuffix);
            }
        }

        log.info("##    明日增量数据表初始化完成, 日期: {}, 分片数: {} ", date, tableShards);
    }


}
